/*
 * @Description: axios 请求封装
 * @version:
 * @Author: m
 * @LastEditors: m
 */
import axios from "axios";
import Qs from "qs";
import { Toast } from "vant";
import { getToken } from "@/utils/auth";
import router from "@/router/index";
import { getQueryString } from "@/utils/queryString";
import global_url from "@/utils/global";

const service = axios.create({
	baseURL: global_url.httpURL,
	timeout: 5000,
	headers: { "Content-Type": "application/x-www-form-urlencoded" },
	withCredentials: true,
});

service.interceptors.request.use(
	(config) => {
		config.data = Qs.stringify(config.data);
		config.data = config.data + "&token=" + getToken();
		return config;
	},
	(error) => {
		console.log(error);
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	(response) => {
		const res = response.data;

		console.log(res);

		if (res.code === 300) {
			router.push({
				path: "/login",
				query: {
					code: getQueryString("code"),
				},
			});
			return Toast.fail("用户身份验证失效");
		} else if (res.code === 400) {
			Toast.fail("服务器发生错误");
			return Promise.reject(new Error(res.message || "Error"));
		} else {
			return res;
		}
	},
	(error) => {
		Toast.fail("网络连接错误");
		return Promise.reject(error);
	}
);

export default service;
